package com.ktwlsoft.archivemanage.service.utils.pdf;

import com.alibaba.fastjson.JSONObject;
import com.lowagie.text.pdf.BaseFont;
import com.ktwlsoft.archivemanage.service.img.FileStorageService;
import com.ktwlsoft.archivemanage.service.utils.FileUtils;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import javax.annotation.PostConstruct;
import java.io.*;

/**
 * PDFUtils
 *
 * @author zhuhe on 2019/11/8 16:48
 * @version 1.0
 */
@Component
public class PDFUtils {

    private final FileStorageService i_fileStorageService;

    public static FileStorageService fileStorageService;

    private final FreeMarkerConfigurer i_freeMarkerConfigurer;

    private static FreeMarkerConfigurer freeMarkerConfigurer;

    public PDFUtils(FileStorageService fileStorageService, FreeMarkerConfigurer i_freeMarkerConfigurer) {
        this.i_fileStorageService = fileStorageService;
        this.i_freeMarkerConfigurer = i_freeMarkerConfigurer;
    }


    @PostConstruct
    public void init(){
        fileStorageService = this.i_fileStorageService;
        freeMarkerConfigurer = this.i_freeMarkerConfigurer;
    }

    /**
     * 生成pdf on 2019/11/8 16:45
     *
     * @param data 传入html的数据
     * @param modelName ftl文件名
     * @param filename pdf文件名
     */
    public static String generatePdf(JSONObject data, String modelName,String filename){
        //配置路径
        String pash = "pdfFile" + File.separator + data.getLong("id");
        pash = fileStorageService.getStrPath(pash);
        //生成文件夹
        File file = new File(pash);
        if(!file.exists()){
            file.mkdirs();
        }
        OutputStream os = null;
        String htmlPash = "";
        try {
            //新建pdf
            File pdf = new File(pash + File.separator + filename);
            pdf.createNewFile();
            //获取html
            htmlPash = createHtml(modelName,data,pash);
            String html = new File(htmlPash).toURI().toURL().toString();
            os = new FileOutputStream(pdf);
            ITextRenderer renderer = new ITextRenderer();
            //将图片标签转换为Itext自己的图片对象
            renderer.getSharedContext().setReplacedElementFactory(new Base64ImgReplacedElementFactory());
            renderer.getSharedContext().getTextRenderer().setSmoothingThreshold(0);
            renderer.setDocument(html);
            // 解决中文不显示问题
            ITextFontResolver fontResolver = renderer.getFontResolver();
            if("linux".equals(System.getProperty("os.name").toLowerCase())){
                fontResolver.addFont(fileStorageService.getStrPath("font" + File.separator + "simsun.ttc"), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            }else{
                fontResolver.addFont(fileStorageService.getStrPath("font" + File.separator + "simsun.ttc"), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                fontResolver.addFont(fileStorageService.getStrPath("font" + File.separator + "Arial.ttf"), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            }
            renderer.layout();
            renderer.createPDF(os);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(htmlPash != null && !"".equals(htmlPash)) {
                FileUtils.deleteFile(htmlPash);
            }
        }
        return pash + File.separator + filename;
    }

    /**
     * 生成html on 2019/11/8 16:44
     *
     * @param modelName ftl文件名
     * @param data 传入html的数据
     * @return String
     */
    private static String createHtml(String modelName,JSONObject data,String pash)throws Exception{
        Configuration cfg = freeMarkerConfigurer.getConfiguration();
        //指定模板位置
        Template temp = cfg.getTemplate(modelName);
        BufferedWriter writer = new BufferedWriter (new OutputStreamWriter (new FileOutputStream (pash + File.separator + "template.html",true),"UTF-8"));
        temp.process(data, writer);
        writer.close();
        return pash + File.separator + "template.html";
    }
}